import groovy.sql.Sql
import org.crsh.cli.Argument
import org.crsh.cli.Command
import org.crsh.cli.Option
import org.crsh.cli.Usage
import org.crsh.command.InvocationContext

import javax.sql.DataSource

@Usage("Execute SQL scripts using application defined data source")
class sql {


    @Usage("query [-o output] -n named query | select statement")
    @Command
    void query(
            InvocationContext<Object> context,
            @Option(names = ["n", "name"]) String queryName,
            @Option(names = ["o", "out"])String output,
            @Argument String stmt) {

        def ds = getDataSource(context)
        def sql = new Sql(ds)
        def query = stmt
        if (queryName) {
            def lines = new File("/tmp/${queryName}.sql")
                    .readLines()
                    .collect{line -> line.trim()}
            query = lines.join(' ')
        }

    }


















    private static DataSource getDataSource(context) {
        context.attributes["spring.beanfactory"].getBean("dataSource")
    }
}